<template>
  <el-card style="height: 80px">
    <el-form class="form">
      <el-form-item label="用户名：">
        <el-input placeholder="请输入用户名" v-model="keyword"></el-input>
      </el-form-item>
      <el-form-item label="">
        <el-button type="primary" :disabled="!keyword" @click="searchUser">
          搜索
        </el-button>
        <el-button type="primary" @click="resetUser">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin-top: 10px">
    <el-button type="primary" @click="addUser">添加用户</el-button>
    <el-popconfirm title="确认删除这些用户吗?" @confirm="deleteBatchUser">
      <template #reference>
        <el-button type="danger" :disabled="idList">批量删除</el-button>
      </template>
    </el-popconfirm>
    <el-table
      border
      style="margin-top: 10px"
      :data="userArr"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        align="center"
        label=""
        type="selection"
      ></el-table-column>
      <el-table-column
        align="center"
        label="#"
        type="index"
        width="50px"
      ></el-table-column>
      <el-table-column align="center" label="ID" prop="id"></el-table-column>
      <el-table-column
        align="center"
        label="用户名字"
        prop="name"
      ></el-table-column>
      <el-table-column
        align="center"
        label="用户名称"
        prop="username"
      ></el-table-column>
      <el-table-column
        align="center"
        label="用户角色"
        prop="roleName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        align="center"
        label="创建时间"
        prop="createTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        align="center"
        label="更新时间"
        prop="updateTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column align="center" label="操作" width="270px">
        <template #="{ row, $index }">
          <el-button
            type="primary"
            size="small"
            @click="assignRole(row)"
            icon="User"
          >
            分配角色
          </el-button>
          <el-button
            type="warning"
            size="small"
            @click="updateUser(row)"
            icon="Edit"
          >
            编辑
          </el-button>
          <el-popconfirm title="确认删除该用户吗?" @confirm="deleteUser(row)">
            <template #reference>
              <el-button type="danger" size="small" icon="Delete">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 10px"
      :total="total"
      :current-page="pageNo"
      v-model:page-size="pageSize"
      @current-change="getAllUserInfo"
      @size-change="handler"
      layout=" prev, pager, next ,jumper, ->,total, sizes"
      :background="true"
      :page-sizes="[3, 5, 7, 9]"
    ></el-pagination>
  </el-card>
  <!-- 抽屉结构 用于添加 -->
  <el-drawer v-model="drawer">
    <template #header>
      <h4>{{ userParams.id ? '编辑用户' : '添加用户' }}</h4>
    </template>
    <template #default>
      <el-form :model="userParams" :rules="rules" ref="formRef">
        <el-form-item label="用户姓名" prop="username">
          <el-input
            placeholder="请填写用户名字"
            v-model="userParams.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="name">
          <el-input
            placeholder="请填写用户昵称"
            v-model="userParams.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
          <el-input
            placeholder="请填写用户密码"
            v-model="userParams.password"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClick">取消</el-button>
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </div>
    </template>
  </el-drawer>
  <el-drawer v-model="drawer2" title="分配用户角色" :with-header="true">
    <template #default>
      <el-form>
        <el-form-item label="用户名称">
          <el-input :value="userParams.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="用户职位">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-checkbox-group
            v-model="checkedRoles"
            @change="handleCheckedRolesChange"
          >
            <el-checkbox
              v-for="(role, index) in roles"
              :key="index"
              :label="role"
            >
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelRole">取消</el-button>
        <el-button type="primary" @click="confirmRole">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import {
  reqUserInfo,
  reqAddorUpdateUser,
  reqAllRole,
  reqAssignRole,
  reqDeleteUser,
  reqDeleteAllUser,
} from '@/api/acl/user/index'
import { ElMessage, FormInstance } from 'element-plus'
import useLayoutSettingStore from '@/store/modules/setting'
let layoutSettingStore = useLayoutSettingStore()
let pageNo = ref<number>(1)
let pageSize = ref<number>(3)
let total = ref(0)
let userArr = ref([])
let userParams = reactive({
  password: '',
  username: '',
  name: '',
})
// 批量删除的idList
let idList: number[] = []
// 收集用户输入的关键字
let keyword = ref<string>('')
// 职位列表
let roles = ref([])
// 控制抽屉显隐
let drawer = ref<boolean>(false)
let drawer2 = ref<boolean>(false)
// 复选框
const checkAll = ref(false)
const isIndeterminate = ref(true)
let checkedRoles = ref([''])
const handleCheckAllChange = (val: any) => {
  checkedRoles.value = val ? roles.value : []
  isIndeterminate.value = false
}
const handleCheckedRolesChange = (value: string[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === roles.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < roles.value.length
}
const getAllUserInfo = async (pager = 1) => {
  pageNo.value = pager
  let res = await reqUserInfo(pageNo.value, pageSize.value, keyword.value)
  // console.log(res.data.records);
  userArr.value = res.data.records
  total.value = res.data.total
}
const validatorUsername = (rule: any, value: any, callback: any) => {
  // 用户名至少5位
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback(new Error('用户名至少5位'))
  }
}
const validatorName = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('昵称至少2位'))
  }
}
const validatorPassword = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 6) {
    callback()
  } else {
    callback(new Error('密码至少5位'))
  }
}
let rules = {
  username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
  name: [{ required: true, trigger: 'blur', validator: validatorName }],
  password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
}
let formRef = ref<FormInstance>()
onMounted(() => {
  getAllUserInfo()
})
const handler = () => {
  getAllUserInfo()
}
const addUser = () => {
  Object.assign(userParams, {
    password: '',
    username: '',
    name: '',
    id: 0,
  })
  formRef.value?.clearValidate()
  drawer.value = true
}
const updateUser = (row: any) => {
  drawer.value = true
  Object.assign(userParams, row)
  formRef.value?.clearValidate()
}
const confirmClick = async () => {
  await formRef.value?.validate()
  let res: any = await reqAddorUpdateUser(userParams)
  // console.log(res);
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: userParams.id ? '更新成功' : '添加成功',
    })
    drawer.value = false
    getAllUserInfo(userParams.id ? pageNo.value : 1)
  } else {
    ElMessage({
      type: 'error',
      message: '添加失败，用户名可能重复',
    })
  }
}
const cancelClick = () => {
  drawer.value = false
}
const assignRole = async (row: any) => {
  drawer2.value = true
  // console.log(row);
  Object.assign(userParams, row)
  let res: any = await reqAllRole(userParams.id)
  // console.log(res);
  if (res.code == 200) {
    roles.value = res.data.allRolesList
    checkedRoles.value = res.data.assignRoles
    drawer2.value = true
  }
}
const cancelRole = () => {
  drawer2.value = false
}
const confirmRole = async () => {
  let data = {
    roleIdList: checkedRoles.value.map((item) => item.id),
    userId: userParams.id,
  }
  // console.log(data);
  let res: any = await reqAssignRole(data)
  // console.log(res);
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '分配职务成功',
    })
    getAllUserInfo()
    drawer2.value = false
  }
}
const deleteUser = async (row: any) => {
  // console.log(row.id);
  let res: any = await reqDeleteUser(row.id)
  // console.log(res);
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getAllUserInfo()
  }
}
const handleSelectionChange = (val: any) => {
  // console.log(val[0].id);
  idList = val.map((item: any) => item.id)
  console.log(idList)
}

const deleteBatchUser = async () => {
  let res: any = await reqDeleteAllUser(idList)
  // console.log(res);
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '批量删除成功',
    })
    getAllUserInfo()
  }
}
const searchUser = () => {
  getAllUserInfo()
}
const resetUser = () => {
  layoutSettingStore.refresh = !layoutSettingStore.refresh
}
</script>

<style scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
